package com.jhws.business.visitor.service;

import com.jhws.business.aliyun.service.OSSClientService;
import com.jhws.business.visitor.bo.TblVisitorDimBo;
import com.jhws.common.Page;
import com.jhws.core.db.BaseDao;
import com.jhws.core.exception.BizException;
import com.jhws.business.visitor.dao.ITblVisitorDimDAO;
import com.jhws.util.DateUtil;
import com.jhws.util.LogHelper;
import com.jhws.util.file.FileUtil;
import com.jhws.util.ObjectUtils;
import com.jhws.util.StringUtils;
import org.apache.commons.collections.MapUtils;
import org.hibernate.Query;
import org.hibernate.transform.Transformers;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("Duplicates")
public class TblVisitorDimServiceSpringImpl implements ITblVisitorDimService {
    private ITblVisitorDimDAO tblVisitorDimDAO;
    @Resource
    private BaseDao BaseDao;
    @Resource
    private OSSClientService ossClientService;

    public void setTblVisitorDimDAO(ITblVisitorDimDAO tblVisitorDimDAO) {
        this.tblVisitorDimDAO = tblVisitorDimDAO;
    }

    public Page findTblVisitorDim(int start, int num, String whereClause)
            throws Exception {
        return tblVisitorDimDAO.findTblVisitorDim(start, num, whereClause);
    }

    /**
     * 保存访客照片
     *
     * @param bo
     * @return
     * @throws Exception
     */
    public TblVisitorDimBo save(TblVisitorDimBo bo) throws Exception {
        return tblVisitorDimDAO.save(bo);
    }

    /**
     * 条件查询
     *
     * @param whereClause
     * @return
     * @throws Exception
     */
    public List findTblVisitorDimByWhere(String whereClause) throws Exception {
        return tblVisitorDimDAO.findTblVisitorDimByWhere(whereClause);
    }


    /**
     * 查询访客图片
     *
     * @param param
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> findVisitorListApi(Map param) throws Exception {
        String whereClause = "1=1 ";
        int page = MapUtils.getIntValue(param, "page");
        int pageSize = MapUtils.getIntValue(param, "pageSize");
        String commCode = MapUtils.getString(param, "commCode", "");
        String building = MapUtils.getString(param, "building", "");
        String unit = MapUtils.getString(param, "unit", "");
        String floor = MapUtils.getString(param, "floor", "");
        String room = MapUtils.getString(param, "room", "");
        String type = MapUtils.getString(param, "type", "");
        if (StringUtils.isNotEmpty(commCode)) {
            whereClause += " and comm_code = '" + commCode + "'";
        }
        if (StringUtils.isNotEmpty(building)) {
            whereClause += " and building_code = '" + building + "'";
        }
        if (StringUtils.isNotEmpty(unit)) {
            whereClause += " and unit_code = '" + unit + "'";
        }
        if (StringUtils.isNotEmpty(floor)) {
            whereClause += " and floor_code = '" + floor + "'";
        }
        if (StringUtils.isNotEmpty(room)) {
            whereClause += " and room_code = '" + room + "'";
        }
        if (StringUtils.isNotEmpty(type)) {
            whereClause += " and type = '" + type + "'";
        }
        String sql = "select access_device, visitor_date, image_url from tbl_visitor_dim where " + whereClause + " order by visitor_date desc";

        Query query = BaseDao.h().getSessionFactory().getCurrentSession().createSQLQuery(sql);
        if (page > 0) {
            int startNum = (page - 1) * pageSize;
            query.setFirstResult(startNum);
            query.setMaxResults(pageSize);
        }
        query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String, Object>> list = query.list();
        for (Map<String, Object> map : list) {
            String imageUrl = (String) map.get("image_url");
            String url = ossClientService.getVisitorUrl(imageUrl);
            if (!StringUtils.isEmpty(url) && !url.equals(imageUrl)) {
                map.replace("image_url", url);
            }
        }
        return list;
    }

    /**
     * 查询访客图片用于api
     *
     * @param param
     * @return
     * @throws Exception
     */
    public Map<String, Object> findVisitorList(Map param) throws Exception {
        Map<String, Object> result = new HashMap<>();
        boolean isNotPage = MapUtils.getBooleanValue(param, "isNotPage");
        String whereClause = "1=1 ";
        String startDate = MapUtils.getString(param, "startDate", "");
        String endDate = MapUtils.getString(param, "endDate", "");
        String commCode = MapUtils.getString(param, "commCode", "");
        String building = MapUtils.getString(param, "building", "");
        String unit = MapUtils.getString(param, "unit", "");
        String floor = MapUtils.getString(param, "floor", "");
        String room = MapUtils.getString(param, "room", "");
        String type = MapUtils.getString(param, "type", "");
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            whereClause += " and visitor_date >= '" + startDate + " 00:00:00' and visitor_date <='" + endDate + " 23:59:59'";
        } else {
            throw new BizException("日期错误！");
        }

        if (StringUtils.isNotEmpty(commCode)) {
            whereClause += " and comm_code = '" + commCode + "'";
        }
        if (StringUtils.isNotEmpty(building)) {
            whereClause += " and building_code = '" + building + "'";
        }
        if (StringUtils.isNotEmpty(unit)) {
            whereClause += " and unit_code = '" + unit + "'";
        }
        if (StringUtils.isNotEmpty(floor)) {
            whereClause += " and floor_code = '" + floor + "'";
        }
        if (StringUtils.isNotEmpty(room)) {
            whereClause += " and room_code = '" + room + "'";
        }
        if (StringUtils.isNotEmpty(type)) {
            whereClause += " and type = '" + type + "'";
        }

        String sql = "select * from tbl_visitor_dim where " + whereClause + " order by visitor_date desc";
        List<Map<String, Object>> list;
        if (isNotPage) {
            list = BaseDao.j().queryForList(sql);
        } else {
            Page p = BaseDao.queryPage(sql, Map.class);
            list = p.getList();
            result.put("size", p.getTotalNumber());
        }
        for (Map<String, Object> map : list) {
            String imageUrl = (String) map.get("image_url");
            String url = ossClientService.getVisitorUrl(imageUrl);
            if (!StringUtils.isEmpty(url) && !url.equals(imageUrl)) {
                map.replace("image_url", url);
            }
        }
        result.put("list", list);
        result.put("ret_code", 1);
        return result;
    }

	/* 
     *  @create time : 2016-9-26 下午5:34:29
	 *  @author : Alex Tan
	 *  @comments : 局域网本地服务器获取path路径中的本地图片
	 */

    public List<String> getLocalVisitorsUrls(String path, String prefix) {
        String seprator = "/";
        if (File.separatorChar == '\\') {
            seprator = "\\\\";
            prefix = prefix.replace("/", "\\");
        }

        ArrayList<String> paths = new ArrayList<String>();
        ArrayList<String> localPaths = new ArrayList<String>();
        FileUtil.getAllFileName(path, paths, prefix);
        for (String p : paths) {

            String[] strings = p.split(seprator);
            int len = strings.length;
            String newPath = "/visitors/" + strings[len - 6] + "/" + strings[len - 5] + "/" + strings[len - 4] + "/" + strings[len - 3] +
                    "/" + strings[len - 2] + "/" + strings[len - 1];

            localPaths.add(newPath);
        }
        return localPaths;
    }

    //删除3个月之前的数据
    public void delete3Month() {
        String hql = "delete TblVisitorDimBo  where visitor_date <= '" + DateUtil.getDateByFrontMonth(3, DateUtil.TIME_FORMAT) + "'";
        LogHelper.e("------------------>    " + hql);
        BaseDao.executeHql(hql);
    }

}
